package com.pactera.madp.cp.service.sync.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.pactera.madp.cp.api.entity.WorkContactEmployeeEntity;
import com.pactera.madp.cp.api.entity.crm.WorkCustomInfoEntity;
import com.pactera.madp.cp.api.entity.sync.SyncCustomInfoEntity;
import com.pactera.madp.cp.common.constant.Constants;
import com.pactera.madp.cp.common.util.RedisUtil;
import com.pactera.madp.cp.context.SyncStateContext;
import com.pactera.madp.cp.mapper.sync.SyncCustomInfoMapper;
import com.pactera.madp.cp.service.IWorkContactEmployeeService;
import com.pactera.madp.cp.service.WorkCustomInfoService;
import com.pactera.madp.cp.service.sync.CrmCustomSyncBusinessService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@AllArgsConstructor
public class CrmCustomSyncBusinessServiceImpl implements CrmCustomSyncBusinessService {

    private final RedisTemplate redisTemplate;
    private final IWorkContactEmployeeService workContactEmployeeService;
    private final WorkCustomInfoService workCustomInfoService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean syncBusiness() {

        String nowDate = DateUtil.format(new Date(), Constants.DATE_FORMAT);

        // 执行同步业务
        String lockKey = RedisUtil.buildKey(Constants.SYNC_CUSTOM_BUSINESS_LOCK, nowDate);
        try {
            // 获取同步业务的锁
            boolean isLocked = RedisUtil.getLock(lockKey, "1", Constants.EXPIRE_TIME, TimeUnit.SECONDS);
            if (!isLocked) {
                SyncStateContext.get().setSaveLog(false);
                return false;
            }
            log.info("CRM客户业务同步获取锁成功");

            // 获取临时数据
            List<SyncCustomInfoEntity> syncList = (List<SyncCustomInfoEntity>) SyncStateContext.get().getTempData()[3];
            if (syncList.isEmpty()) {
                return false;
            }

            // 查询外部联系人
            List<WorkContactEmployeeEntity> wceList = workContactEmployeeService.list();

            // crm客户业务数据列表
            List<WorkCustomInfoEntity> workList = new ArrayList<>();

            // 比对手机号，相同为行内客户，否则为行外客户
            WorkCustomInfoEntity entity = new WorkCustomInfoEntity();
            syncList.forEach(sc -> {
                boolean isInner = false;
                WorkCustomInfoEntity e = entity.clone();
                BeanUtil.copyProperties(sc, e);

                for (WorkContactEmployeeEntity w : wceList) {
                    String mobile = w.getRemarkMobiles()
                            .replace("[", "")
                            .replace("]", "")
                            .replace("\\\"", "");
                    if (mobile.length() > 11) {
                        mobile = mobile.split(",")[0];
                        if (mobile.length() > 11) {
                            int len = mobile.length();
                            mobile = mobile.substring(len - 11, len);
                        }
                    }
                    if (StrUtil.equals(sc.getMobileTel(), mobile)) {
                        // 行内客户
                        e.setCustType(1);
                        isInner = true;
                        break;
                    }
                }
                if (!isInner) {
                    e.setCustType(2);
                }

                workList.add(e);
            });
            syncList.clear();

            if (workList.isEmpty()) {
                return false;
            }

            // 保存当前同步数据到业务表
            workCustomInfoService.batchSaveAll(workList);
            workList.clear();

            log.info("已同步CRM客户业务数据量：{}", SyncStateContext.get().getTempData()[2]);
        } finally {
            redisTemplate.delete(lockKey);
            log.info("CRM客户业务同步释放锁成功");
        }
        return true;
    }

}
